-module(mes_misc).
-export([get/1]).

-include("../measure_defs.hrl").

-record(res_sum, {e_m, err}).

dump(#res_sum{e_m = EM, err = Err}, #results{ms = L, name = N, avg = Avg, classname = CN}) ->
    io:format("Name: ~p ClassName =~p~n", [N, CN]),
    io:format("L=~w~navg = ~p e_m = ~p err = ~p~n", [L, Avg, EM, Err]).

get_error(#results{ms = L, ops = Ops, avg = Avg0} = R) ->
    BigAvg = lists:sum(L)/length(L),
    BigDif = lists:max(lists:map(
                fun (Item) ->
                    abs(Item-BigAvg)
                end,
                L
             )),
    Dif = BigDif/Ops,
    Err = BigDif/BigAvg*100,
    
    Avg0 = BigAvg/Ops, % assert
    
    RS = #res_sum{e_m = Dif, err = Err},
    dump(RS, R),
    RS.

max(A, B) when A > B ->
    A;
max(_, B) ->
    B.

max_sum([], R) ->
    R;
max_sum([#res_sum{e_m = EM1, err = Err1}|L],
         #res_sum{e_m = EM2, err = Err2}) ->
    max_sum(
        L,
        #res_sum{e_m = max(EM1, EM2), err = max(Err1, Err2)}).

get_scenario(List) ->
    Results = lists:filter(fun (Rec) -> element(1, Rec) =:= results end, List),
    
    Summaries = lists:map(fun (Item) -> get_error(Item) end, Results),
%     {Difs, Errs} = lists:unzip(MaxDifs),
%     MaxDif = lists:max(Difs),
%     MaxErr = lists:max(Errs),
    #res_sum{e_m = Err1, err = Err2} = max_sum(Summaries, #res_sum{e_m = -1, err = -1}),
    Avg = lists:sum(lists:map(fun (#results{avg = X}) -> X end, Results))/length(Results),
    
    #tail_data{} = lists:last(List),
    lists:map(
        fun (X = #tail_data{}) ->
            X#tail_data{
                mes_err1 = Err1,
                mes_err2 = Err2,
                avg = Avg
            };
        (X) ->
            X
        end,
        List).
%                     
%     io:format("List = ~p~n", [List]),
%     io:format("MaxDifs = ~p~n", [MaxDifs]).

get(#all_results{res_list = Scenarios} = A) ->
    L2 =
        lists:map(
            fun (Scenario) ->
                get_scenario(Scenario)
            end, Scenarios),
    A#all_results{res_list = L2}.
